package com.java2104.controller;

import com.java2104.entity.DeliveryAddress;
import com.java2104.service.DeliveryAddressService;
import com.java2104.service.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DeliveryAddressController {

    @Autowired
    private DeliveryAddressService deliveryAddressService;

    @Autowired
    private UserMessageService userMessageService;

    @GetMapping({"/address_detail/{id}","/address_detail.html"})
    public String addressDetail(@PathVariable Integer id, Model model){
        model.addAttribute("id",id);
        return "address_detail";
    }

    @GetMapping({"/address_add","/address_add.html"})
    public String addressAdd(Model model){
        model.addAttribute("userList",userMessageService.list());
        return "address_add";
    }

    @GetMapping({"/address_list","/address_list.html"})
    public String userList(){
        return "address_list";
    }

    @RequestMapping("/address/list")
    @ResponseBody
    public List<DeliveryAddress> userMessageList(String phoneNumber, String addressee){
        return deliveryAddressService.list(phoneNumber,addressee);
    }

    @RequestMapping("/address/one/{id}")
    @ResponseBody
    public DeliveryAddress one(@PathVariable Integer id){
        return  deliveryAddressService.getById(id);
    }

    @RequestMapping("/address/delete/{id}")
    public String delete(@PathVariable Integer id){
        deliveryAddressService.removeById(id);
        return "redirect:/address_list";
    }

    @RequestMapping(path = "/address/update",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String updateAddress(@RequestBody DeliveryAddress deliveryAddress){
        return deliveryAddressService.updateAddress(deliveryAddress)?"success":"fail";
    }

    @PostMapping("/address_add")
    public String addressAdd(Model model,DeliveryAddress deliveryAddress){
        if(deliveryAddressService.saveAddress(deliveryAddress)>0){
            model.addAttribute("ret_msg","添加成功");
        }else {
            model.addAttribute("ret_msg","添加失败");
        }
        return addressAdd(model);
    }
}
